package com.zhoug.demo.audiorecorder;

import android.Manifest;
import android.media.AudioFormat;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.zhoug.audiorecorder.AudioRecordConfig;
import com.zhoug.audiorecorder.ZAudioRecorder;
import com.zhoug.common.permission2.ZPermissions;
import com.zhoug.common.utils.FileUtils;
import com.zhoug.common.utils.LogUtils;
import com.zhoug.common.utils.TimeUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;


public class MainActivity extends MyBaseActivity {
    private static final String TAG = ">>>MainActivity";
    private final Handler mTimerHandler = new Handler(Looper.getMainLooper());
    private ZAudioRecorder mAudioRecorder;
    private TextView mTvDuring;
    private TextView mBtnRecord;
    private ISaveWAVFile mSaveWAV;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main;
    }

    @Override
    protected void findViews() {
        mTvDuring = findViewById(R.id.tv_during);
        mBtnRecord = findViewById(R.id.btn_record);
    }

    @Override
    protected void onCreate1(Bundle savedInstanceState) {
//        SileroVAD sileroVAD=new SileroVAD();
//        sileroVAD.loadModel(this);
        VADSaveWAVFile vadSaveWAVFile = new VADSaveWAVFile(getApplicationContext());
        SplitSaveWAVFile splitSaveWAVFile = new SplitSaveWAVFile(getApplicationContext());
        splitSaveWAVFile.setSplitFile(false);
        splitSaveWAVFile.setSplitTime(10_000);
//        mSaveWAV = vadSaveWAVFile;
        mSaveWAV = splitSaveWAVFile;
        mSaveWAV.setListener(new ISaveWAVFile.Listener() {
            @Override
            public String getOutputFilePath() {
                return MainActivity.this.getOutputFilePath();
            }

            @Override
            public void onSaveFileFinish(String path, long startTime, long endTime) {
                LogUtils.d(TAG, "onSaveFileFinish: path=" + path + ",startTime=" + startTime + ",endTime=" + endTime);
            }
        });

        AudioRecordConfig config = new AudioRecordConfig();
        config.setAudioSource(MediaRecorder.AudioSource.MIC)
                .setSampleRate(16000)
                .setChannelConfig(AudioFormat.CHANNEL_IN_MONO)
                .setAudioFormat(AudioFormat.ENCODING_PCM_16BIT);

        mAudioRecorder = new ZAudioRecorder(config);
        mAudioRecorder.setListener(new ZAudioRecorder.OnAudioDataAvailableListener() {
            @Override
            public void onAudioDataAvailable(@NonNull byte[] data) {
//                LogUtils.d(TAG, "onAudioDataAvailable: "+data.length);
//                float predict = sileroVAD.predict(data);
                mSaveWAV.onAudioDataAvailable(data);

            }

            /**
             * 错误回掉
             *
             * @param code
             * @param msg
             */
            @Override
            public void onError(int code, String msg) {
                LogUtils.e(TAG, "onError: " + msg);
                mBtnRecord.setText("开始录音");
                mBtnRecord.setSelected(false);
            }
        });

        //开始/停止录音
        mBtnRecord.setOnClickListener(v -> {
            ZPermissions.with(this)
                    .setPermissions(Manifest.permission.RECORD_AUDIO,
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .setDescription("需要录音权限和存储权限")
                    .setCallback((success, arrayList, arrayList1) -> {
//                        if(success){
                        if (mAudioRecorder.isRecording()) {
                            mBtnRecord.setText("开始录音");
                            mBtnRecord.setSelected(false);
                            mAudioRecorder.stopRecording();
                            mSaveWAV.stopWriteFile();
                        } else {
                            mBtnRecord.setText("停止录音");
                            mBtnRecord.setSelected(true);
                            mAudioRecorder.startRecording();
                        }
//                        }

                    })
                    .request();

        });

    }

    /**
     * 创建录音文件保存路径
     * @return
     */
    private String getOutputFilePath() {
        // 创建录音文件
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
        String timeStamp = simpleDateFormat.format(new Date());
        String fileName = "recording_" + timeStamp + ".wav";
//        File audioFolder = FileUtils.getAppExternalFilesDir(context, "record");
        String audioFolder = FileUtils.getExternalFolder("0recording");
        return new File(audioFolder, fileName).getAbsolutePath();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mSaveWAV!=null){
            mSaveWAV.release();
        }
    }

}